package com.yeskery.nut.util;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

/**
 * 环境工具类
 * @author YESKERY
 * 2024/6/17
 */
public class EnvironmentUtils {

    /** 标志符号 */
    private static final char FLAG_SYMBOL = '$';

    /** 开始符号 */
    private static final char START_SYMBOL = '{';

    /** 结束符号 */
    private static final char END_SYMBOL = '}';

    /** 标志符号字符串 */
    private static final String FLAG_SYMBOL_STR = "$";

    /** 开始符号字符串 */
    private static final String START_SYMBOL_STR = "{";

    /** 结束符号字符串 */
    private static final String END_SYMBOL_STR = "}";

    /**
     * 私有化构造方法
     */
    private EnvironmentUtils(){
    }

    /**
     * 获取占位符数据
     * @param string 字符串
     * @return 占位符数据
     */
    public static Set<String> getPlaceHolders(String string) {
        if (StringUtils.isEmpty(string)) {
            return Collections.emptySet();
        }
        int lastFlagStartIndex = -1;
        Set<String> placeHolders = new HashSet<>();
        for (int i = 0; i < string.length(); i++) {
            char c = string.charAt(i);
            if (c == FLAG_SYMBOL) {
                if (i + 1 < string.length() && string.charAt(i + 1) == START_SYMBOL) {
                    lastFlagStartIndex = i;
                }
            } else if (c == END_SYMBOL) {
                if (lastFlagStartIndex != -1) {
                    String placeHolder = string.substring(lastFlagStartIndex, i + 1);
                    if (!StringUtils.isEmpty(placeHolder) && placeHolder.length() > 3) {
                        String placeHolderName = placeHolder.substring(2, placeHolder.length() - 1);
                        if (!placeHolderName.contains(FLAG_SYMBOL_STR) && !placeHolderName.contains(START_SYMBOL_STR)
                                && !placeHolderName.contains(END_SYMBOL_STR)) {
                            placeHolders.add(placeHolder);
                        }
                    }
                }
                lastFlagStartIndex = -1;
            }
        }
        return placeHolders;
    }
}
